<template>
  <div>
    <el-form v-model="form" :inline="true">
      <el-form-item>
        <el-input v-model="form.message" placeholder="Message" clearable class="w-200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="form.authorEmail"
          placeholder="Author Email"
          clearable
          class="w-150px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="form.authorFullname"
          placeholder="Author Fullname"
          clearable
          class="w-150px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="form.startDate"
          type="date"
          placeholder="开始时间"
          :editable="false"
          class="w-150px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="form.endDate"
          type="date"
          placeholder="结束时间"
          :editable="false"
          class="w-150px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <RepoSelect v-model="form.repo" />
      </el-form-item>
      <el-form-item>
        <EngineerSelect v-model="selectedEngineer" />
      </el-form-item>

      <el-form-item>
        <el-input
          v-model.number="form.minTotalChanges"
          placeholder="Min Changes"
          type="number"
          clearable
          class="w-150px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model.number="form.maxTotalChanges"
          placeholder="Max Changes"
          type="number"
          clearable
          class="w-150px"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column label="贡献时间" min-width="80">
        <template #default="{ row }">
          <span>{{ row.authoredDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="贡献者" min-width="60">
        <template #default="{ row }">
          <div style="line-height: 16px">
            <span class="fw-bold fs-6">{{ row.authorFullname }}</span>
            <br />
            <span class="fs-8 text-gray-500" :title="row.authorEmail">
              {{ row.authorEmail.substring(0, 20) + (row.authorEmail.length > 20 ? '...' : '') }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="工程师">
        <template #default="{ row }">
          <div style="line-height: 16px">
            <span class="fw-bold fs-6">{{ row.engineerName }}</span>
            <KTIcon
              :icon-name="roleSettings[row.engineerRole].icon"
              :icon-class="`fs-5 text-${roleSettings[row.engineerRole].color} ms-2`"
            />
            <span
              :class="`badge badge-light-${roleSettings[row.engineerRole].color} ms-1`"
              :title="row.engineerRole"
            >
              {{ roleSettings[row.engineerRole].name }}
            </span>
            <br />
            <span class="fs-8 text-gray-500">
              {{ row.departmentPath ? row.departmentPath.substring(10) : '' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="仓库" min-width="80">
        <template #default="{ row }">
          <a :href="row.repoWebUrl" target="_blank">
            <span class="fs-8 text-gray-500">
              ({{ row.gitInstance == 'beijing' ? '北京' : '成都' }})
            </span>
            <span class="fs-6">
              {{ row.repoName }}
            </span>
          </a>
        </template>
      </el-table-column>
      <el-table-column label="Message" min-width="150">
        <template #default="{ row }">
          <a :href="row.webUrl" target="_blank">
            <i
              class="fa-duotone fa-solid"
              :class="
                row.commitType == '1' ? 'fa-code-commit text-primary' : 'fa-code-merge text-warning'
              "
              :title="row.commitType == '1' ? '提交' : '合并'"
            >
            </i>
            <span class="ms-2" :title="row.message">
              {{ row.message.substring(0, 20) + (row.message.length > 20 ? '...' : '') }}
            </span>
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="totalChanges" label="代码" min-width="80" align="right">
        <template #default="{ row }">
          <span class="text-success fs-8">
            <i class="fa-solid fa-plus"></i> {{ row.additions }}
          </span>
          <span class="text-danger fs-8 ms-2">
            <i class="fa-solid fa-minus"></i> {{ row.deletions }}
          </span>
          <span class="ms-2">{{ row.totalChanges }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { roleSettings } from '@/utils/roleUtils';
import RepoSelect from '@/components/common/RepoSelect.vue';
import EngineerSelect from '@/components/common/EngineerSelect.vue';
import KTIcon from '@/core/helpers/kt-icon/KTIcon.vue';
import type { RepoValue } from '@/types/business/repository';

interface FormData {
  message: string;
  authorEmail: string;
  authorFullname: string;
  startDate: Date | null;
  endDate: Date | null;
  repo: RepoValue | null;

  minTotalChanges: number | null;
  maxTotalChanges: number | null;
}

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const form = ref<FormData>({
  message: '',
  authorEmail: '',
  authorFullname: '',
  startDate: null,
  endDate: null,
  repo: null,

  minTotalChanges: null,
  maxTotalChanges: null,
});

const selectedEngineer = ref<{ value: number; label: string } | null>(null);

const search = () => {
  const formatDate = (date: Date | null) => {
    if (!date) return null;
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    message: form.value.message,
    authorEmail: form.value.authorEmail,
    authorFullname: form.value.authorFullname,
    startDate: formatDate(form.value.startDate),
    endDate: formatDate(form.value.endDate),
    gitInstance: form.value.repo ? form.value.repo.gitInstance : null,
    repositoryId: form.value.repo ? form.value.repo.repositoryId : null,
    engineerId: selectedEngineer.value?.value || '',

    minTotalChanges: form.value.minTotalChanges,
    maxTotalChanges: form.value.maxTotalChanges,
  };
  axios
    .get('/api/commit-log/page', { params })
    .then((response) => {
      tableData.value = response.data.records;
      total.value = response.data.total;
    })
    .catch((error) => {
      console.error(error);
    });
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  search();
};

onMounted(() => {
  search();
});
</script>
